package com.service.atf.reply.service;

import com.service.atf.base.exception.TFException;
import com.service.atf.base.model.Account;
import com.service.atf.base.model.TFBingo;
import com.service.atf.base.utils.ATFConstants;
import com.service.atf.base.utils.ATFLogger;
import com.service.atf.reply.ac.AccountManager;
import com.service.atf.reply.core.IReadExecutor;
import com.luotao.devp.base.utils.MD5Util;

import java.util.Map;

/**
 * User: luotao
 * Date: 12-3-21
 * Time: 17:00:00
 */
public class BingoService4 implements IReadExecutor<TFBingo> {
    @Override
    public boolean isNotify() {
        return true;
    }

    private static final String KEY_BALC_CHARGE = "balcCharge";

    private static final String KEY_BALC_AWARD = "balcAward";

    public void initOut(Map out) {
        out.put(KEY_BALC_CHARGE, 0);
        out.put(KEY_BALC_AWARD, 0);
    }


    @Override
    public void execute(boolean recover, AccountManager accountManager, TFBingo bingo, Map out) {
        ATFLogger.sysdebug("enter bingo !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

        if (bingo.getSubAwardMoney() > bingo.getAwardTradeMoney()) {
            String msg = "兑奖金额大于中奖金额" + bingo.getCustomerCode();
            throw new TFException(1, msg);
        }


//   * REPLY中，如果用户中奖并且已经登录，则修改AC中的临时中奖金额（临时中奖金额=
//   * 临时中奖金额-兑付金额），修改AC中用户的奖金余额(奖金余额=奖金余额+兑付金额)。
//   *
        Account account = accountManager.getBussAccount(bingo.getCustomerCode());
        if (account != null) {
            long awardMoney = bingo.getAwardTradeMoney();
            String md5Bingo = MD5Util.MD5Encode(bingo.getMappedFlowId() + awardMoney);
            if (!account.getMd5Bingo().equals(md5Bingo)) {
                String msg = "兑奖校验失败," + bingo.getCustomerCode();
                ATFLogger.sysdebug(msg);
                throw new TFException(ATFConstants.ATF_BINGO_MD5_ERR, msg);
            }
            if (account.getTmpAward() > 0) {
                account.setBalcAward(account.getBalcAward() + bingo.getSubAwardMoney());
                account.setTmpAward(account.getTmpAward() - bingo.getSubAwardMoney());
            } else {
                account.setBalcAward(account.getBalcAward() + bingo.getAwardTradeMoney());
            }
            ATFLogger.sysdebug("兑奖时将交易流水设置为空!!!!!!!!!!!!!");
            account.setMd5Bingo("");
            account.setLastFlowId("");
            accountManager.updateAccount(account);
            out.put(KEY_BALC_CHARGE, account.getBalcCharge());
            out.put(KEY_BALC_AWARD, account.getBalcAward());
        } else {

        }
    }
}
